# -*- coding:utf-8 -*-
"""
@Time : 2020-12-15 11:54
@Author: langengel
@Des: 服务商注册
"""

import json
from fastapi import Request
from models.saas import Service, User, Wechat
from saas.response.BaseResponse import fail, success
from saas.utils.utils import zfill
from validator.service import ServiceCreate
from validator.user import WxInfo


async def service_reg(req: Request, service_info: ServiceCreate):
    """
    服务商微信注册
    :param req: Request
    :param service_info: ServiceCreate
    :return: success
    """
    wx_user = await req.app.state.cache.get(service_info.web_code + '-userinfo')
    if not wx_user:
        return fail(msg="页面超时,请重新扫码", code=3001)
    wechat_user = WxInfo(**json.loads(wx_user))
    # 创建服务商
    add_service = await create_service(wechat_user=wechat_user, service_name=service_info.service_name)
    if add_service:
        await req.app.state.cache.delete(service_info.web_code + '-userinfo')
        await req.app.state.code.delete(service_info.web_code)
        return success(msg="服务商注册成功")

    return fail(msg="服务商注册失败")


async def create_service(wechat_user: WxInfo, service_name: str):
    """
    服务商创建
    :param wechat_user: WechatUser
    :param service_name: 服务商名称
    :return: boolean
    """

    if not wechat_user.openid:
        return False
    # 创建服务商
    add_service = await Service().create(service_name=service_name)
    # 追加业务ID
    await add_service.update_from_dict({"s_id": zfill("1", add_service.pk, 10)}).save()
    # 创建超级管理员
    add_user = await User().create(
        nickname=wechat_user.nickname,
        headimgurl=wechat_user.headimgurl,
        service=add_service,
        type=True,
        u_status=1

    )
    # 追加业务ID
    await add_user.update_from_dict({"u_id": zfill('8', add_user.pk, 10)}).save()
    # 创建用户微信
    await Wechat().create(**wechat_user.dict(), service=add_service, user=add_user)

    return True


async def user_bind(req: Request, web_code: str):
    """
    服务商微信注册
    :param req: Request
    :param web_code: ServiceCreate
    :return: success
    """
    pass
    # 获取微信用户信息
    wx_user = await req.app.state.cache.get(web_code + '-userinfo')
    # # 获取操作内容
    action = await req.app.state.cache.get(web_code)
    if not action:
        return fail(msg="二维码超时,请重新向服务商管理员索取")
    # 提取微信用户信息
    if not wx_user:
        return fail(msg="二维码超时,请重新向服务商管理员索取")
    wechat_user = WxInfo(**json.loads(wx_user))
    # 提取操作数据
    action_data = json.loads(action)
    uid = action_data.get('uid')
    sid = action_data.get('sid')
    if not uid or not sid:
        return fail(msg="你没有此权限，请向服务商管理员申请")
    # 验证服务商
    service = await Service().get_or_none(id=sid)
    if not service:
        return fail(msg="你没有此权限，请向服务商管理员申请")
    # 验证用户
    user = await User().get_or_none(service=service, id=uid)
    if not user:
        return fail(msg="你没有此权限，请向服务商管理员申请")
    # 用户微信当前服务商是否绑定
    # check_wechat = await Wechat().filter(service=service, openid=wechat_user.openid).all()
    # if check_wechat:
    #     return fail(msg="你已在当前服务商绑定过其他账户，请更换其他微信")

    # 获取当前用户微信表对象
    wechat = await Wechat().get_or_none(user=user)
    if not wechat:
        return fail(msg="你没有此权限，请向服务商管理员申请")
    # 执行更新
    await wechat.update_from_dict(wechat_user.dict()).save()
    # 更新用户头像和昵称
    await user.update_from_dict({"nickname": wechat_user.nickname, "headimgurl": wechat_user.headimgurl}).save()

    await req.app.state.cache.delete(web_code + '-userinfo')
    await req.app.state.code.delete(web_code)
    return success(msg="绑定成功")
